import { STR_SETTINGS } from "@/constant";
import type { Settings } from "@/types";

export const defaultSettings: Settings = {
  searchEngine: "baidu",
  navLinks: [
    {
      id: "default-1",
      name: "GitHub",
      url: "https://github.com",
      icon: "https://github.githubassets.com/favicons/favicon.svg",
    },
    {
      id: "default-2",
      name: "MDN",
      url: "https://developer.mozilla.org",
      icon: "https://developer.mozilla.org/favicon-48x48.png",
    },
  ],
  background: "",
};

interface NavLinkData {
  [STR_SETTINGS]: string;
}

const isInExtension =
  typeof chrome !== "undefined" && chrome.runtime && typeof chrome.runtime.id === "string" && chrome.runtime.id !== "";

export const storage = {
  // chrome.storage.local.set 保存后的数据变成了 以数字为键的对象（如 {"0": {...}, "1": {...}}），而不是预期的数组, 需要单独处理
  // 因此直接存储 json 字符串更容易
  async set(value: string): Promise<void> {
    if (isInExtension) {
      const data: NavLinkData = { [STR_SETTINGS]: value };
      return new Promise((resolve, reject) => {
        chrome.storage.local.set(data, () => {
          if (chrome.runtime.lastError) {
            reject(chrome.runtime.lastError);
          } else {
            resolve();
          }
        });
      });
    } else {
      return new Promise((resolve) => {
        localStorage.setItem(STR_SETTINGS, JSON.stringify(value));
        resolve();
      });
    }
  },

  // 同步获取（实际存在异步到同步的转换）
  async get(): Promise<Settings> {
    if (isInExtension) {
      async function getStorageData(keys: string[]) {
        return new Promise((resolve, reject) => {
          chrome.storage.local.get(keys, (result) => {
            if (chrome.runtime.lastError) {
              reject(chrome.runtime.lastError);
            } else {
              resolve(result[STR_SETTINGS] as string);
            }
          });
        });
      }

      let res = defaultSettings;
      const data = (await getStorageData([STR_SETTINGS])) as string;
      if (data) res = JSON.parse(data) as Settings;
      return res;
    } else {
      const data = localStorage.getItem(STR_SETTINGS);
      return data ? (JSON.parse(data) as Settings) : defaultSettings;
    }
  },
};
